﻿using System;
using Biz.Buffer;
using Biz.EF.Gateway.Monitor;
using Biz.EF.Platform;
using Hjt212Parser;
using log4net;

namespace Biz.Process
{
    public class DownlineFlowTriggerMonitor
    {
        private static readonly ILog Log = LogManager.GetLogger(typeof(DownlineFlowTriggerMonitor));
        public static void Trigger(PlatformContext pCtx, GatewayMonitorContext gCtx, string content)
        {
            try
            {
                var mn = Parser.GetStringByKey("MN", content);
                if (string.IsNullOrEmpty(mn)) return;
                if (mn.Contains("TINZSC20170017TZ83206001")) return;
                if (mn.Contains("TINZSC20170027TZ83206002")) mn = "TINZSC20170017TZ83206001";
                if (mn.Contains("TINZSC20170020TZ83206006")) mn = "TINZSC20170011TZ83206005";
                var datatime = Parser.GetDateTimeByKey("DataTime", content);
                if (datatime == null) return;
                var now = DateTime.Now;

                if (Math.Abs((now - datatime.Value).TotalMinutes) > 15)
                {
                    Log.Warn("数据时间和当前时间差15分钟以上，认为是补传数据，不发流量触发指令。");
                    return;
                }
                var rtd = Parser.GetDoubleByKey("w00000-Rtd", content);
                if (rtd == null) return;
                var letport = CommonInformation.GetLetportByMn(mn);
                if (letport == null) return;

                var systemSetup = CommonInformation.GetSystemSetupByName("流量触发");
                if (string.IsNullOrEmpty(systemSetup?.参数内容)) return;
                var limitValue = int.Parse(systemSetup.参数内容.Trim());
                Log.Info("流量触发值:" + limitValue + "\n" + mn + "当前流量:" + rtd);

                if (rtd < limitValue)
                {
                    return;
                }
                systemSetup = CommonInformation.GetSystemSetupByName("流量开始触发");
                if (string.IsNullOrEmpty(systemSetup?.参数内容))
                {
                    Log.Error("没有设置流量开始触发值(分钟)");
                    return;
                }
                var delayTimeToAnalysis = int.Parse(systemSetup.参数内容.Trim());
                //Log.Info("流量开始触发值(分钟):" + delayTimeToAnalysis);
                systemSetup = CommonInformation.GetSystemSetupByName("两次流量触发");
                if (string.IsNullOrEmpty(systemSetup?.参数内容))
                {
                    Log.Warn("没有设置两次流量触发(分钟)");
                    return;
                }
                var nextTime = int.Parse(systemSetup.参数内容.Trim());
                //Log.Info("两次流量触发(分钟):" + nextTime);
                TriggerInfo info = TriggerInfoBuffer.GetInfo(mn);
                //首次执行，将对应信息添加到缓冲中
                if (info == null)
                {
                    info = new TriggerInfo
                    {
                        IsSent = false,
                        TriggerDateTime = now,
                        SentDateTime = now.AddMinutes(delayTimeToAnalysis),
                        NextSendDateTime = now.AddMinutes(nextTime + delayTimeToAnalysis)
                    };
                    TriggerInfoBuffer.AddInfo(mn, info);
                }
                if (info.IsSent) return;
                //现在时间大于下次执行时间，重置//TODO增加了 rtd < limitValue重置
                // if (now > info.NextSendDateTime)// || rtd < limitValue)
                {
                    info.IsSent = false;
                    info.TriggerDateTime = now;
                    info.SentDateTime = info.TriggerDateTime.AddMinutes(delayTimeToAnalysis);
                    info.NextSendDateTime = info.TriggerDateTime.AddMinutes(nextTime + delayTimeToAnalysis);
                }
                TriggerInfoBuffer.AddInfo(mn, info);
            }
            catch (Exception ex)
            {
                Log.Error(ex);
            }
        }

        //public static void Trigger(PlatformContext pCtx, GatewayMonitorContext gCtx)
        //{
        //    try
        //    {
        //        var mns = TriggerInfoBuffer.GetInfoKeys();
        //        foreach (var mn in mns)
        //        {
        //            var letport = CommonInformation.GetLetportByMn(mn);
        //            if (letport == null) continue;
        //            var systemSetup = CommonInformation.GetSystemSetupByName("流量开始触发");
        //            if (string.IsNullOrEmpty(systemSetup?.参数内容))
        //            {
        //                Log.Error("没有设置流量开始触发值(分钟)");
        //                return;
        //            }
        //            var delayTimeToAnalysis = int.Parse(systemSetup.参数内容.Trim());
        //            Log.Debug("流量开始触发值(分钟):" + delayTimeToAnalysis);
        //            systemSetup = CommonInformation.GetSystemSetupByName("两次流量触发");
        //            if (string.IsNullOrEmpty(systemSetup?.参数内容))
        //            {
        //                Log.Error("没有设置两次流量触发(分钟)");
        //                return;
        //            }
        //            TriggerInfo info = TriggerInfoBuffer.GetInfo(mn);
        //            //首次执行，将对应信息添加到缓冲中
        //            if (info == null || info.IsSent)
        //            {
        //                continue;
        //            }
        //            var now = DateTime.Now;

        //            if (!info.IsSent && now >= info.SentDateTime && now < info.NextSendDateTime)
        //            {
        //                info.IsSent = true;
        //                //todo:下发指令
        //                try
        //                {
        //                    流量触发记录 record = new 流量触发记录
        //                    {
        //                        企业基本信息ID = letport.企业基本信息ID,
        //                        设备信息ID = letport.ID,
        //                        时间 = now
        //                    };
        //                    pCtx.流量触发记录.Add(record);
        //                    pCtx.SaveChanges();
        //                }
        //                catch (Exception e)
        //                {
        //                    Log.Error(e);
        //                }
        //                try
        //                {
        //                    var result = "QN=" + now.ToString("yyyyMMddHHmmssfff") +
        //                                 ";ST=32;CN=4016;PW=123456;MN=" + mn + ";Flag=5;CP=&&&&";
        //                    Log.Info(result);
        //                    send_ctr_cmd record = new send_ctr_cmd
        //                    {
        //                        cn = "4016",
        //                        is_sent = false,
        //                        mn = mn,
        //                        qn = now.ToString("yyyyMMddHHmmssfff"),
        //                        send_string = result,
        //                        send_time = now,
        //                        sent_time = now
        //                    };
        //                    gCtx.send_ctr_cmd.Add(record);
        //                    gCtx.SaveChanges();
        //                }
        //                catch (Exception e)
        //                {
        //                    Log.Error(e);
        //                }
        //            }
        //            TriggerInfoBuffer.AddInfo(mn, info);
        //        }

        //    }
        //    catch (Exception ex)
        //    {
        //        Log.Error(ex);
        //    }
        //}
    }
}
